package cn.com.nes.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 复制工具类
 *
 * @Author: ShenWei
 * @Date: 2024/04/02/14:52
 */
public class CopyUtils {

    public static <S, T> Map<String, Object> listToMap(String key, List<S> sourceList, Class<T> clazz) {
        List<T> destList = copyList(sourceList, clazz);

        Map<String, Object> map = new HashMap<>();
        map.put(key,destList);
        return map;
    }

    public static <S, T> List<T> copyList(List<S> sourceList, Class<T> clazz){
        //使用orika复制工具将sourceList集合复制到destList集合中
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<T> destList = mapperFactory.getMapperFacade().mapAsList(sourceList,clazz);
        return destList;
    }

    public static <S, T> Page<T> copyPage(Page<S> sourcePage, Class<T> clazz){
        //使用orika复制工具将SourceRecords集合复制到returnRecords集合中
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<T> records = mapperFactory.getMapperFacade().mapAsList(sourcePage.getRecords(),clazz);

        // 准备Page
        Page<T> page = new Page<>();
        sourcePage.setRecords(null);
        BeanUtils.copyProperties(sourcePage, page);
        page.setRecords(records);
        return page;
    }

}
